package Request;

use strict;
use CGI qw(:standard);

use constant DEBUG => "FALSE";

sub new {
    
    # Get the class name
    my $stInvocant = shift(@_);
    my $stClass = ref($stInvocant) || $stInvocant;

    # Create the current instance and bless into class
    my $rSelf = { };
    bless($rSelf,$stClass);

    $rSelf->{query} = CGI->new();
    $rSelf->{cookies} = [];
    $rSelf->{user} = { };

    return $rSelf;
}


sub getRealm {

    my $rSelf = shift(@_);
    return $rSelf->{realm};

}

sub getActionParam {
  my $rSelf = shift(@_);
  return '_action';
}

# deprecated... confusing. see getActionParam
sub getActionName {

    my $rSelf = shift(@_);
    return '_action';
}

sub action {
    my $rSelf = shift(@_);
    my $stAction = shift(@_) || undef;

    if ($stAction) {
	$rSelf->{query}->param('_action',$stAction);
    }

    return $rSelf->{query}->param('_action') || 'DefaultAction';
}

sub param {

    my $rSelf = shift(@_);
    return $rSelf->{query}->param(@_);
}

sub delete {

    my $rSelf = shift(@_);
    return $rSelf->{query}->delete(@_);
}

sub cookie {

    my $rSelf = shift(@_);
    my %hArgs = ( @_ );

    if (exists $hArgs{'-value'}) {

	# print "Cookie being set ...\n";

	my $rCookies = $rSelf->{cookies};
	push(@$rCookies,$rSelf->{query}->cookie(@_));
	
    }

    return $rSelf->{query}->cookie(@_);
}

sub reply {

    my $rSelf = shift(@_);
    my $rResponse = shift(@_);

    print header( -cookie=> $rSelf->{cookies} );

    if ($rResponse) {

	my $stResponse = $rResponse->{view}->draw();

	if (DEBUG eq "TRUE") {
	    
	    # chop off </body></html> tags
	    $stResponse =~ s/<\/body>//;
	    $stResponse =~ s/<\/html>//;

	    # append name/value pairs
	    $stResponse .= "<br><br><hr width='30%'>\n";
	    $stResponse .= "<ul><b>Params</b>\n";
	    my $stKey;
	    foreach $stKey ($rSelf->param()) {

		$stResponse .= "<li>$stKey = " . $rSelf->param($stKey) . "\n";
	    }
	    $stResponse .= "</ul>\n<ul><b>Cookies</b>\n";
	    foreach $stKey ($rSelf->cookie()) {
	      $stResponse .= "<li>$stKey = " . $rSelf->cookie($stKey) . "\n";
	    }
	    $stResponse .= "</ul>\n</body>\n</html>\n";
	  }
	
	print $stResponse;
    }

    #
    # This might be a more general purpose way of responding to requests than the above
    #
    #    $rViewWrapper->setViewFileHandle(FILE_HANDLE);
    
    #    while (<FILE_HANDLE>) {
    #	print $_;
    #    }

}

1;
